package com.pet.serve.service;

import com.pet.serve.entity.Goods;
import com.pet.serve.entity.Pets;
import com.pet.serve.entity.Shopcar;
import com.pet.serve.repository.GoodsRepository;
import com.pet.serve.repository.PetsRepository;
import com.pet.serve.repository.ShopcarRepository;
import com.pet.serve.request.ShopcarRequest;
import com.pet.serve.response.ApiResponse;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Service
public class ShopcarService {

    private final ShopcarRepository shopcarRepository;

    private final GoodsRepository GoodsRepository;

    private final PetsRepository PetsRepository;

    public ShopcarService(ShopcarRepository shopcarRepository, GoodsRepository GoodsRepository, PetsRepository PetsRepository) {
        this.shopcarRepository = shopcarRepository;
        this.GoodsRepository = GoodsRepository;
        this.PetsRepository = PetsRepository;
    }


    // 查找指定用户的购物车
    public List<Shopcar> findByUsername(String username) {
        return shopcarRepository.findByUsername(username);
    }

    // 查找购物车中指定商品或宠物
    public Shopcar findByUsernameAndItem(String username, Long goodid, Long petid) {
        return shopcarRepository.findByUsernameAndItem(username, goodid, petid);
    }

    // 根据商品状态查找购物车中的商品
    public List<Shopcar> findByUsernameAndGoodsStatus(String username, String status) {
        return shopcarRepository.findByUsernameAndGoodsStatus(username, status);
    }

    // 根据宠物状态查找购物车中的宠物
    public List<Shopcar> findByUsernameAndPetsStatus(String username, String status) {
        return shopcarRepository.findByUsernameAndPetsStatus(username, status);
    }

    // 更新购物车中商品数量和总价
    @Transactional
    public void updateShopcarItem(Long id, Integer num, BigDecimal totalPrice) {
        shopcarRepository.updateShopcarItem(id, num, totalPrice);
    }


    // 删除指定用户的购物车
    @Transactional
    public void deleteByUsername(String username) {
        shopcarRepository.deleteByUsername(username);
    }

    // 添加商品或宠物到购物车
    public ApiResponse addToCart(ShopcarRequest request) {
        // 检查用户是否已存在购物车项
        Optional<Shopcar> existingShopcar = shopcarRepository.findByUsernameAndGoodidAndPetid(
                request.getUsername(), request.getGoodid(), request.getPetid());

        if (request.getPetid() != null) {
            // 处理宠物
            Pets pet = PetsRepository.findById(request.getPetid()).orElse(null);
            if (pet == null || !pet.getStatus().equals(Pets.PetStatus.saling)) {
                return new ApiResponse(false, "宠物不可添加到购物车", null);
            }

            if (existingShopcar.isPresent()) {
                return new ApiResponse(false, "宠物已达上限", null);
            } else {
                Shopcar shopcar = new Shopcar();
                shopcar.setUsername(request.getUsername());
                shopcar.setPets(pet);
                shopcar.setNum(1); // 默认数量为1
                shopcar.setTotalPrice(pet.getPrice()); // 设置宠物的价格为总金额
                shopcarRepository.save(shopcar);
                return new ApiResponse(true, "成功加入购物车！", null);
            }
        } else if (request.getGoodid() != null) {
            // 处理商品
            Goods goods = GoodsRepository.findById(request.getGoodid()).orElse(null);
            if (goods == null || !(goods.getStatus().equals("saling"))){
                return new ApiResponse(false, "商品不可添加到购物车", null);
            }

            if (existingShopcar.isPresent()) {
                Shopcar existingItem = existingShopcar.get();
                int newNum = existingItem.getNum() + request.getNum();
                if (newNum > goods.getNum()) {
                    return new ApiResponse(false, "库存不足", null);
                }
                existingItem.setNum(newNum);
                existingItem.setTotalPrice(goods.getPrice().multiply(new BigDecimal(newNum))); // 更新总金额
                shopcarRepository.save(existingItem);
                return new ApiResponse(true, "成功更新购物车！", null);
            } else {
                if (request.getNum() > goods.getNum()) {
                    return new ApiResponse(false, "库存不足", null);
                }
                Shopcar shopcar = new Shopcar();
                shopcar.setUsername(request.getUsername());
                shopcar.setGoods(goods);
                shopcar.setNum(request.getNum());
                shopcar.setTotalPrice(goods.getPrice().multiply(new BigDecimal(request.getNum()))); // 设置总金额
                shopcarRepository.save(shopcar);
                return new ApiResponse(true, "成功加入购物车！", null);
            }
        }

        return new ApiResponse(false, "请求无效", null);
    }

    public void deleteByShopcarid(Long id) {
        shopcarRepository.deleteById(id);
    }
}
